# Replication Material for "Social Capital, Institutional Rules 
#     and Constitutional Amendment Rates"
# William Blake, Joseph Cozza, Dave Armstrong and Amanda Friesen
#
# before running, execute setup.r first
#
# This file produces tables A1, A2 and A3

## Cross-national Models
cndat <- import("crossnational_replication.dta")

## Table A1

R <- cor(cndat[,c("govConfid", "partyConfid", "courtConfid", "groups", "civicAct")], use="complete")
R <- apply(R, 2, function(x)sprintf("%.3f", x))
rownames(R) <- colnames(R)
R[upper.tri(R)] <- ""
diag(R) <- ""
R <- R[-1, -ncol(R)]
noquote(R)


## Table A2 
wvs_r <- import("wvs_cor_data.dta")
wvs_rmat <- cor(wvs_r %>% select(ends_with("_all")), wvs_r %>% select(ends_with("pre14")), use="pair")
tibble(variable = colnames(wvs_rmat), r = diag(wvs_rmat))

## Tarabar and Young Simulation

sim <- function(n, nv){
  mat <- matrix(runif(n*(nv+1)), ncol=(nv+1))
  m <- lm(mat[,1] ~ mat[,-1])
  r2 <- cor(mat[,1], fitted(m))^2
  sig <- sum(summary(m)$coefficients[,4] < .05)
  c(r2 = r2, sig=sig)
}

set.seed(519)
r27 <- t(replicate(10000, sim(72, 27)))
r7 <- t(replicate(10000, sim(57, 7)))

colMeans(r27)
colMeans(r7)

apply(r27, 2, max)
apply(r7, 2, max)

